package com.example.demo;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.demo.entity.User;
import com.example.demo.util.CloseDefaultStyleUtil;

import  java.text.SimpleDateFormat;
import java.util.Date;


public class Login extends CloseDefaultStyleUtil implements View.OnClickListener {
    private Spinner languageSpinner; // 语言选择下拉框
    private TextView clockText;      // 时间点问候语
    private TextView versionInfo;    //版本信息

    //登录布局
    private LinearLayout liLogin;
    private EditText accountName;    // 登录账户
    private EditText accountPwd;     // 登录密码
    private Button  continueButton;    // 提交按钮
    private TextView registText;     // 去注册

    //注册布局
    private LinearLayout liRegist;
    private ImageView rebackImg;
    private EditText registUsername;
    private EditText registEmail;
    private EditText registPwd;
    private EditText registConfirmPwd;
    private Button submitBtn;        //注册提交

    // 注册成功后，邮箱验证布局
    private LinearLayout liEmailValidate;
    private EditText validateCode;
    private Button   validateBtn;
    private TextView validateFailInfo;

    //邮箱验证成功布局
    private LinearLayout liSuccessValidate;
    private ImageView    successRebeck;

    private int tagLanguage = 0 ;    // 标记位，让语言选择开始不跳出弹窗


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        bindElement(); //绑定组件
        clockGreet();  //问候语显示

        languageSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String currValue=(String)languageSpinner.getSelectedItem();
                if(tagLanguage!=0){ // 刚开始不弹出默认语言
                    Toast.makeText(Login.this,currValue,Toast.LENGTH_SHORT).show();
                }
                tagLanguage=1;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

    }

    /**
     * 代码简写：绑定组件
     */

    private void bindElement(){
        languageSpinner = findViewById(R.id.language_spinner);
        clockText       = findViewById(R.id.clock_text);
        versionInfo     =findViewById(R.id.version_info);
       //登录布局
        liLogin         = findViewById(R.id.login);
        accountName     = findViewById(R.id.account_name);
        accountPwd      = findViewById(R.id.account_pwd);
        continueButton    = findViewById(R.id.continue_btn);
        registText      = findViewById(R.id.regist_text);

        //注册布局
        liRegist        =findViewById(R.id.regist);
        rebackImg       =findViewById(R.id.regist_reback);
        registUsername  =findViewById(R.id.regist_username);
        registEmail     =findViewById(R.id.regist_accountname);
        registPwd       =findViewById(R.id.regist_pwd);
        registConfirmPwd=findViewById(R.id.regist_confirm_pwd);
        submitBtn       =findViewById(R.id.submit_btn);

        // 注册成功邮箱验证布局
        liEmailValidate =findViewById(R.id.li_validate);
        validateCode    =findViewById(R.id.validate_code);
        validateBtn     =findViewById(R.id.submit_code_btn);
        validateFailInfo=findViewById(R.id.validate_fail_info);

        //邮箱验证成功布局
        liSuccessValidate=findViewById(R.id.success_validate);
        successRebeck   =findViewById(R.id.regist_success_reback);

        registText.setOnClickListener(this);
        rebackImg.setOnClickListener(this);
        submitBtn.setOnClickListener(this);
        validateBtn.setOnClickListener(this);
        successRebeck.setOnClickListener(this);
        continueButton.setOnClickListener(this);



    }
    private void clockGreet(){
        SimpleDateFormat  formatter   =   new   SimpleDateFormat   ("yyyy年MM月dd日   HH:mm:ss");
        Date curDate =  new Date(System.currentTimeMillis());
        String str  =  formatter.format(curDate);
        Log.i("user101:当前时间",str);
        int currHour=curDate.getHours();
        if(currHour>1&&currHour<11){
            clockText.setText("Good Morning");
        }else if (currHour>11&&currHour<13){
            clockText.setText("Noon good");
        }else if (currHour>13&&currHour<19){
            clockText.setText("Good afternoon");
        }else clockText.setText("Good evening");
    }
    public boolean registEditTextValidate(){
        String username = registUsername.getText().toString().trim();
        String email    = registEmail.getText().toString().trim();
        String password = registPwd.getText().toString().trim();
        String confirmPwd =registConfirmPwd.getText().toString().trim();
        Log.i("log102:用户名-邮箱-合法性",username+"-"+email+"-"+username.matches("[0-9A-Za-z]{1,9}$"));
        //验证输入的用户名是否在1-9之间并且是数字和字母
        if (!username.matches("[0-9A-Za-z]{1,9}$")){
            Toast.makeText(Login.this,"不合法，请输入1-9位数字和字母组合的字符串",Toast.LENGTH_SHORT).show();
            return false;
        }
        boolean emailValid=email.matches("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
        if(!emailValid){
            Toast.makeText(Login.this,"不合法，请输入正确的邮箱",Toast.LENGTH_SHORT).show();
            return false;
        }
        if (password==null||password.length()<1){
            Toast.makeText(Login.this,"请输入密码",Toast.LENGTH_SHORT).show();
            return false;
        }
        if (password==null||password.length()<1){
            Toast.makeText(Login.this,"请输入密码",Toast.LENGTH_SHORT).show();
            return false;
        }
        if(confirmPwd==null||confirmPwd.length()<1){
            Toast.makeText(Login.this,"请确认密码",Toast.LENGTH_SHORT).show();
            return false;
        }
        if(!confirmPwd.equals(password)){
            Toast.makeText(Login.this,"密码和确认密码不相等，请确认",Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }
    public boolean loginValidate(String email,String pwd){
        // User user=sql.getUserByEmail() 通过邮箱查询用户
        boolean emailValid=email.matches("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
        if(!emailValid){
            Toast.makeText(Login.this,"不合法，请输入正确的邮箱",Toast.LENGTH_SHORT).show();
            return false;
        }
        if(email.equals("demo@demo.com")&&pwd.equals("demo")){
            return true;
        }
        return false;
    }

    @Override
    public void onClick(View v) {
      int eleId=v.getId();
      switch (eleId){
          case R.id.continue_btn:{
              String email=accountName.getText().toString().trim();
              String pwd=accountPwd.getText().toString().trim();
              if(accountName==null||accountName.getText().toString().length()<1||accountPwd==null||accountPwd.getText().toString().length()<1){
                  Toast.makeText(Login.this,"请输入邮箱和密码",Toast.LENGTH_SHORT).show();
                  break;
              }
              if(loginValidate(email,pwd)){
                  Toast.makeText(Login.this,"登录成功",Toast.LENGTH_SHORT).show();
                  Intent intent=new Intent(this,MainActivity.class);
                  Bundle bundle=new Bundle();
                  bundle.putSerializable("email",email);
                  intent.putExtras(bundle);
                  startActivity(intent);
              }else {
                  Toast.makeText(Login.this,"邮箱和密码错误，请检查",Toast.LENGTH_SHORT).show();
              }
              break;
          }
          // 点击去注册后使得登录组件消失，注册组件出现
          case R.id.regist_text:{
              liLogin.setVisibility(View.GONE);
              liRegist.setVisibility(View.VISIBLE);
              break;
          }
          // 点击×后注册组件消失，登录组件出现
          case R.id.regist_reback:{
              liRegist.setVisibility(View.GONE);
              liLogin.setVisibility(View.VISIBLE);

              break;
          }
          // 点击注册组件中的提交按钮，对输入框进行判断
          case R.id.submit_btn:{
              boolean goOn=registEditTextValidate();
              if(goOn){
                  liRegist.setVisibility(View.GONE);
                  liLogin.setVisibility(View.GONE);
                  liEmailValidate.setVisibility(View.VISIBLE);
                  versionInfo.setVisibility(View.INVISIBLE);
              }
              break;
          }
          // 邮箱验证提交按钮
          case R.id.submit_code_btn:{
              if(validateCode==null||validateCode.getText().toString().trim().length()<1){
                  Toast.makeText(Login.this,"请先输入邮箱验证码",Toast.LENGTH_SHORT).show();
                  break;
              }
              String code=validateCode.getText().toString().trim();
              // getSystemCode(),获得系统code
              if(code.equals("1234")){
                  liSuccessValidate.setVisibility(View.VISIBLE);
                  liRegist.setVisibility(View.GONE);
                  liLogin.setVisibility(View.GONE);
                  liEmailValidate.setVisibility(View.GONE);
                  versionInfo.setVisibility(View.INVISIBLE);
                  break;
              }else {
                  validateFailInfo.setVisibility(View.VISIBLE);
                  break;
              }

          }
          //验证成功返回
          case R.id.regist_success_reback:{
              liLogin.setVisibility(View.VISIBLE);
              liRegist.setVisibility(View.GONE);
              liEmailValidate.setVisibility(View.GONE);
              liSuccessValidate.setVisibility(View.GONE);
              versionInfo.setVisibility(View.VISIBLE);
              accountName.setText(registEmail.getText().toString());
              accountPwd.setText(registPwd.getText().toString());
              break;
          }
      }

    }
}